#pragma once
#include "looper.hpp"
#include "sink.hpp"
#include <vector>
#include <atomic>
#include <mutex>
#include <type_traits>
#include <cstdarg>
#include <unordered_map>
namespace yd
{
    class logger
    {
    public:
        enum class Type
        {
            LOGGER_SYNC = 0,
            LOGGER_ASYNC
        };
        using ptr = std::shared_ptr<logger>;
        logger(const std::string &name,
               formatter::ptr formatter,
               std::vector<log_sink::ptr> &sinks,
               log_level ::value level = log_level::value::DEBUG) : _name(name), _level(level), _formatter(formatter),
                                                                    _sinks(sinks.begin(), sinks.end())
        {
        }
        std::string logger_name() { return _name; }
        void debug(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(log_level::value::DEBUG) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(log_level::value::DEBUG, file, line, fmt, al);
            va_end(al);
        }
        void info(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(log_level::value::INFO) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(log_level::value::INFO, file, line, fmt, al);
            va_end(al);
        }
        void warn(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(log_level::value::WARN) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(log_level::value::WARN, file, line, fmt, al);
            va_end(al);
        }
        void error(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(log_level::value::ERROR) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(log_level::value::ERROR, file, line, fmt, al);
            va_end(al);
        }
        void fatal(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(log_level::value::FATAL) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(log_level::value::FATAL, file, line, fmt, al);
            va_end(al);
        }

    public:
        class Builder
        {
        public:
            using ptr = std::shared_ptr<Builder>;
            Builder() : _level(log_level::value::DEBUG),
                        _logger_type(logger::Type::LOGGER_SYNC) {}
            void buildLoggerName(const std::string &name) { _logger_name = name; }
            void buildLoggerLevel(log_level::value level) { _level = level; }
            void buildLoggerType(logger::Type type) { _logger_type = type; }
            void buildFormatter(const std::string pattern) { _formatter = std::make_shared<formatter>(pattern); }
            void buildFormatter(const formatter::ptr &formatter) { _formatter = formatter; }
            template <typename SinkType, typename... Args>
            void buildSink(Args &&...args)
            {
                auto sink = factory::create<SinkType>(std::forward<Args>(args)...);
                _sinks.push_back(sink);
            }
            virtual logger::ptr build() = 0;

        protected:
            logger::Type _logger_type;
            std::string _logger_name;
            log_level ::value _level;
            formatter::ptr _formatter;
            std::vector<log_sink ::ptr> _sinks;
        };

    protected:
        bool shouldLog(log_level ::value level) { return level >= _level; }
        void log(log_level::value level, const char *file, size_t line, const char *fmt, va_list al)
        {
            char *buf;
            std::string msg;
            int len = vasprintf(&buf, fmt, al);
            if (len < 0)
            {
                msg = "格式化数据失败";
            }
            else
            {
                msg.assign(buf, len);
                free(buf);
            }

            log_msg lm(_name, file, line, std::move(msg), level);
            std::stringstream ss;
            _formatter->format(ss, lm);
            logIt(std::move(ss.str()));
        }
        virtual void logIt(const std::string &msg) = 0;
        std::mutex _mutex;
        std::string _name;
        formatter::ptr _formatter;
        std::vector<log_sink::ptr> _sinks;
        std::atomic<log_level::value> _level;
    };

    class Synclogger : public logger
    {
    public:
        using ptr = std::shared_ptr<Synclogger>;
        Synclogger(const std::string &name,
                   formatter ::ptr formatter,
                   std::vector<log_sink::ptr> &sinks,
                   log_level ::value level = log_level::value::DEBUG) : logger(name, formatter, sinks, level)
        {
            std::cout << log_level::to_string(level) << " 同步日志器: " << name << "创建成功...\n";
        }

    private:
        void logIt(const std::string &msg)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            if (_sinks.empty())
                return;
            for (auto &it : _sinks)
            {
                it->log(msg.c_str(), msg.size());
            }
        }
    };
    class AsyncLogger : public logger
    {
    public:
        using ptr = std::shared_ptr<AsyncLogger>;
        AsyncLogger(const std::string &name,
                    formatter::ptr formatter,
                    std::vector<log_sink ::ptr> &sinks,
                    log_level ::value level = log_level::value::DEBUG) : logger(name, formatter, sinks, level),
                                                                         _looper(std::make_shared<async_looper>(std::bind(&AsyncLogger::backendLogIt, this, std::placeholders::_1)))
        {
            std::cout << log_level::to_string(level) << "异步日志器: " << name << "创建成功...\n";
        }

    protected:
        virtual void logIt(const std::string &msg)
        {
            _looper->push(msg);
        }
        void backendLogIt(buffer &msg)
        {
            if (_sinks.empty())
            {
                return;
            }
            for (auto &it : _sinks)
            {
                it->log(msg.begin(), msg.read_ablesize());
            }
        }

    protected:
        async_looper::ptr _looper;
    };
    // 局部的日志器，受到作用域限定的在使用的时候
    class LocalLoggerBuilder : public logger::Builder
    {
    public:
        virtual logger::ptr build()
        {
            if (_logger_name.empty())
            {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            if (_formatter.get() == nullptr)
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<formatter>();
            }
            if (_sinks.empty())
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            logger::ptr lp;
            if (_logger_type == logger::Type::LOGGER_ASYNC)
            {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            else
            {
                lp = std::make_shared<Synclogger>(_logger_name, _formatter, _sinks, _level);
            }
            return lp;
        }
    };
    // 单例管理日志器类
    class loggerManager
    {
    public:
        static loggerManager &getInstance()
        {
            static loggerManager lm;
            return lm;
        }
        bool has_logger(const std::string name)
        {
            // 所以要记住容器的操作是线程不安全的喔
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _loggers.find(name);
            if (it == _loggers.end())
            {
                return false;
            }
            return true;
        }
        void add_logger(const std::string name, const logger::ptr logger)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _loggers.insert({name,logger});
        }
        logger::ptr get_logger(const std::string &name)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _loggers.find(name);
            if (it == _loggers.end()) {
                return logger::ptr();
            }
            return it->second;
        }
        
        logger::ptr rootLogger() {
            std::unique_lock<std::mutex> lock(_mutex);
            return _root_logger;
        }

    private:
        loggerManager()
        {
            std::unique_ptr<LocalLoggerBuilder> llb(new LocalLoggerBuilder());
            llb->buildLoggerName("root");
            llb->buildLoggerType(logger::Type::LOGGER_SYNC);
            _root_logger = llb->build();
            _loggers.insert({_root_logger->logger_name(), _root_logger});
        }
        loggerManager(loggerManager &) = delete;
        loggerManager &operator=(const loggerManager &) = delete;

    private:
        std::mutex _mutex;
        std::unordered_map<std::string, logger::ptr> _loggers;
        logger::ptr _root_logger;
    };
    class GlobalLoggerBuilder: public logger::Builder {
    public:
        virtual logger::ptr build() {
            if (_logger_name.empty()) {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            //assert(loggerManager::getInstance().has_logger(_logger_name) == false);
            if (_formatter.get() == nullptr) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<formatter>();
            }
            if (_sinks.empty()) {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            logger::ptr lp;
            if (_logger_type == logger::Type::LOGGER_ASYNC) {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level);
            }else {
                lp = std::make_shared<Synclogger>(_logger_name, _formatter, _sinks, _level);
            }
            loggerManager::getInstance().add_logger(_logger_name, lp);
            return lp;
        }
};
}